package vip.gnloypp.easy.multimedia.client;

import com.alibaba.fastjson.JSON;
import vip.gnloypp.easy.multimedia.data.attribute.*;
import vip.gnloypp.easy.multimedia.data.dto.AudioInfo;
import vip.gnloypp.easy.multimedia.data.dto.FFStream;
import vip.gnloypp.easy.multimedia.data.dto.FFmpegInfo;
import vip.gnloypp.easy.multimedia.data.dto.VideoInfo;
import vip.gnloypp.easy.multimedia.data.enums.VideoSize;
import vip.gnloypp.easy.multimedia.util.MultimediaFileUtils;
import vip.gnloypp.easy.multimedia.util.MultimediaRuntimeUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author GuoNanLin
 * @date 2020-10-29
 */
public class FFmpegClient {

    /**
     * ffmpeg bin 目录地址
     */
    private String ffmpegBinPath = null;

    public FFmpegClient() {
    }

    public FFmpegClient(String ffmpegBinPath) {
        this.ffmpegBinPath = ffmpegBinPath;
    }

    /**
     * ffmpeg命令ffprobe,需设置ffmpeg环境变量
     */
    private static final String FFPROBE = "ffprobe";

    /**
     * ffmpeg命令ffmpeg,需设置ffmpeg环境变量
     */
    private static final String FFMPEG = "ffmpeg";

    /**
     * 创建大小为 1 的固定线程池，同时执行任务的只有一个,
     * 其它的任务都放在LinkedBlockingQueue中排队等待执行
     */
    ExecutorService executorService = Executors.newSingleThreadExecutor();


    /**
     * 获取视频信息
     *
     * @param tempDirectory 临时文件目录
     * @param inputFileName 视频文件名
     * @return 文件信息
     */
    public FFmpegInfo getInfo(String tempDirectory, String inputFileName) {
        if (!MultimediaFileUtils.checkFileName(inputFileName)) {
            throw new RuntimeException("输入文件名格式错误");
        }

        StringBuilder command = new StringBuilder();

        command.append(Optional.ofNullable(ffmpegBinPath).orElse("") + FFPROBE);
        command.append(" -v quiet -print_format json -show_format -show_streams ");
        command.append(MultimediaFileUtils.getFilePath(tempDirectory, inputFileName));

        String response = MultimediaRuntimeUtils.exec(command.toString());

        FFmpegInfo fFmpegInfo = JSON.parseObject(response, FFmpegInfo.class);

        if (fFmpegInfo.getStreams() == null) {
            throw new RuntimeException("文件不存在");
        }

        List<FFStream> streams = fFmpegInfo.getStreams();
        for (FFStream ffStream : streams) {
            if ("audio".equals(ffStream.getCodecType())) {
                AudioInfo audioInfo = new AudioInfo();
                audioInfo.setCodecName(ffStream.getCodecName());
                audioInfo.setCodecType(ffStream.getCodecType());
                audioInfo.setDuration(ffStream.getDuration());
                audioInfo.setBitRate(ffStream.getBitRate());
                audioInfo.setSampleRate(ffStream.getSampleRate());
                audioInfo.setChannels(ffStream.getChannels());
                fFmpegInfo.setAudioInfo(audioInfo);
            } else if ("video".equals(ffStream.getCodecType())) {
                VideoInfo videoInfo = new VideoInfo();
                videoInfo.setCodecName(ffStream.getCodecName());
                videoInfo.setCodecType(ffStream.getCodecType());
                videoInfo.setWidth(ffStream.getWidth());
                videoInfo.setHeight(ffStream.getHeight());
                videoInfo.setFrameRate(ffStream.getFrameRate());
                videoInfo.setDuration(ffStream.getDuration());
                videoInfo.setBitRate(ffStream.getBitRate());
                videoInfo.setNbFrames(ffStream.getNbFrames());
                String rFrameRate = ffStream.getrFrameRate();
                String[] split = rFrameRate.split("/");
                videoInfo.setFrameRate(Integer.valueOf(split[1]) == 0 ? 0 :
                        (Integer.valueOf(split[0]) / Integer.valueOf(split[1])));
                fFmpegInfo.setVideoInfo(videoInfo);
            }
        }
        return fFmpegInfo;
    }

    /**
     * 获取封面图
     *
     * @param tempDirectory    临时文件目录
     * @param inputFileName    视频文件名
     * @param outputFileSuffix 输出文件后缀名
     * @return 封面文件名
     */
    public String createCover(String tempDirectory, String inputFileName, String outputFileSuffix) {
        if (!MultimediaFileUtils.checkFileName(inputFileName)) {
            throw new RuntimeException("输入文件名格式错误");
        }

        // 设置封面图格式
        String suffix = outputFileSuffix == null ? ".jpg" : outputFileSuffix;

        String outputFileName = MultimediaFileUtils.createFileName(suffix);

        StringBuilder command = new StringBuilder();
        command.append(Optional.ofNullable(ffmpegBinPath).orElse("") + FFMPEG);

        command.append(" -i ");

        command.append(MultimediaFileUtils.getFilePath(tempDirectory, inputFileName));

        command.append(" -ss 1 -t 1 -r 1 -f image2 ");

        command.append(MultimediaFileUtils.getFilePath(tempDirectory, outputFileName));

        MultimediaRuntimeUtils.exec(command.toString());

        return outputFileName;
    }

    /**
     * 获取封面图
     *
     * @param tempDirectory 临时文件目录
     * @param inputFileName 视频文件名
     * @return 封面文件名
     */
    public String createCover(String tempDirectory, String inputFileName) {
        return this.createCover(tempDirectory, inputFileName, null);
    }


    /**
     * 将任务放入执行队列中
     *
     * @param tempDirectory         临时文件目录
     * @param inputFileName         输入的文件名
     * @param compressionAttributes 压缩参数
     * @return 输出文件名
     */
    public String putCompressionTask(String tempDirectory, String inputFileName,
                                     CompressionAttributes compressionAttributes) {
        // 生成输出文件名
        String suffix = MultimediaFileUtils.getSuffix(inputFileName);
        String outputFileName = MultimediaFileUtils.createFileName(suffix);

        this.executeTask(tempDirectory, inputFileName, compressionAttributes, outputFileName);
        return outputFileName;
    }

    /**
     * 将任务放入执行队列中
     *
     * @param tempDirectory         临时文件目录
     * @param inputFileName         输入的文件名
     * @param compressionAttributes 压缩参数
     * @param outputFileName        输出的文件名
     * @return 输出文件名
     */
    public String putCompressionTask(String tempDirectory, String inputFileName,
                                     CompressionAttributes compressionAttributes, String outputFileName) {
        this.executeTask(tempDirectory, inputFileName, compressionAttributes, outputFileName);
        return outputFileName;
    }

    /**
     * 添加压缩任务
     */
    private void executeTask(String tempDirectory, String inputFileName, CompressionAttributes compressionAttributes,
                             String outputFileName) {
        executorService.execute(new Runnable() {
            public void run() {
                compressionVideo(tempDirectory, inputFileName, compressionAttributes, outputFileName);
            }
        });
    }

    /**
     * 压缩视频文件
     *
     * @param tempDirectory         临时文件目录
     * @param inputFileName         原视频文件名
     * @param compressionAttributes 压缩参数
     * @param outputFileName        压缩视频文件名
     */
    private void compressionVideo(String tempDirectory, String inputFileName,
                                  CompressionAttributes compressionAttributes, String outputFileName) {


        if (!MultimediaFileUtils.checkFileName(inputFileName)) {
            throw new RuntimeException("输入文件名格式错误");
        }
        if (!MultimediaFileUtils.checkFileName(outputFileName)) {
            throw new RuntimeException("输出文件名格式错误");
        }

        if (compressionAttributes == null) {
            throw new RuntimeException("缺少压缩参数");
        }


        String progressUrl = compressionAttributes.getProgressUrl();
        if (progressUrl == null) {
            throw new RuntimeException("缺少压缩完成回调URL");
        }

        VideoAttributes videoAttributes = compressionAttributes.getVideoAttributes();
        AudioAttributes audioAttributes = compressionAttributes.getAudioAttributes();

        // 获取原视频信息
        FFmpegInfo info = this.getInfo(tempDirectory, inputFileName);
        VideoInfo videoInfo = info.getVideoInfo();
        AudioInfo audioInfo = info.getAudioInfo();

        StringBuilder command = new StringBuilder();

        command.append(Optional.ofNullable(ffmpegBinPath).orElse("") + FFMPEG);

        // 设置视频源
        command.append(" -i ");
        command.append(MultimediaFileUtils.getFilePath(tempDirectory, inputFileName));
        command.append(" ");

        // 设置视频属性
        if (videoAttributes != null && videoInfo != null) {

            // 设置视频编码
            if (videoAttributes.getCodec() != null) {
                command.append("-c:v ");
                command.append(videoAttributes.getCodec().getCode());
                command.append(" ");
            }

            // 设置视频帧率
            if (this.isSetUp(videoInfo.getFrameRate(), videoAttributes.getMaxFps())) {
                command.append("-r ");
                command.append(videoAttributes.getMaxFps());
                command.append(" ");
            }

            // 设置视频比特率
            if (this.isSetUp(videoInfo.getBitRate(), videoAttributes.getMaxBitRate())) {
                command.append("-b:v ");
                command.append(videoAttributes.getMaxBitRate());
                command.append(" ");
            }

            // 设置视频宽度
            VideoSize videoSize = videoAttributes.getVideoSize();
            if (videoSize != null) {
                command.append("-s ");
                command.append(videoSize.getCode());
                command.append(" ");
            }

            // 设置视频时长
            if (this.isSetUp(Double.valueOf(videoInfo.getDuration()).intValue(), videoAttributes.getMaxDuration())) {
                command.append("-t ");
                command.append(videoAttributes.getMaxDuration());
                command.append(" ");
            }


        }

        // 设置音频属性
        if (audioAttributes != null && audioInfo != null) {
            // 设置音频比特率
            if (this.isSetUp(audioInfo.getBitRate(), audioAttributes.getMaxBitRate())) {
                command.append("-b:a ");
                command.append(audioAttributes.getMaxBitRate());
                command.append(" ");
            }

            // 设置音频采样率
            if (this.isSetUp(audioInfo.getSampleRate(), audioAttributes.getMaxSamplingRate())) {
                command.append("-ar ");
                command.append(audioAttributes.getMaxSamplingRate());
                command.append(" ");
            }
        }

        command.append(MultimediaFileUtils.getFilePath(tempDirectory, outputFileName));

        command.append(" -progress ");

        command.append(progressUrl);

        MultimediaRuntimeUtils.exec(command.toString());
    }


    /**
     * 截取文件（截取相应时长 start秒 - end秒）
     *
     * @param tempDirectory 临时文件目录
     * @param inputFileName 输入文件名
     * @param start         截取开始时间 单位s
     * @param end           截取结束时间 单位s
     * @return 输出文件名
     */
    public String copy(String tempDirectory, String inputFileName, Integer start, Integer end) {
        if (!MultimediaFileUtils.checkFileName(inputFileName)) {
            throw new RuntimeException("输入文件名格式错误");
        }
        if (start == null || end == null) {
            throw new RuntimeException("缺少必要参数");
        }

        String suffix = MultimediaFileUtils.getSuffix(inputFileName);
        String outputFileName = MultimediaFileUtils.createFileName(suffix);

        StringBuilder command = new StringBuilder();

        command.append(Optional.ofNullable(ffmpegBinPath).orElse("") + FFMPEG);
        command.append(" -i ");
        command.append(MultimediaFileUtils.getFilePath(tempDirectory, inputFileName));
        command.append(" -ss ");
        command.append(start);
        command.append(" -c copy -to ");
        command.append(end);
        command.append(" ");
        command.append(MultimediaFileUtils.getFilePath(tempDirectory, outputFileName));

        MultimediaRuntimeUtils.exec(command.toString());

        return outputFileName;
    }

    /**
     * 判断是否设置属性
     *
     * @param originalParameter 原视频属性
     * @param targetParameter   目标属性
     */
    private Boolean isSetUp(Integer originalParameter, Integer targetParameter) {
        if (originalParameter == null || targetParameter == null) {
            return false;
        }
        if (originalParameter <= targetParameter) {
            return false;
        }
        return true;
    }

    /**
     * 图片转视频
     */
    public String img2Video(Img2VideoAttributes attr) {
        return MultimediaRuntimeUtils.exec(ffmpegBinPath +
                "ffmpeg -framerate 1/" + attr.getImgSeconds() +
                " -i " + attr.getImgFolderMatch() +
                " -c:v libx264 -preset veryslow " +
                " -r 30 " +
                " -pix_fmt yuv420p " + attr.getOutputFilePath());
    }

    /**
     * 视频添加文本
     */
    public String videoAddText(VideoAddTextAttributes attr) {
        return MultimediaRuntimeUtils.exec(ffmpegBinPath +
                "ffmpeg -i " + attr.getInputFilePath() +
                " -vf \"drawtext=text='" + attr.getText() + "'" +
                ":fontfile=" + attr.getFontFile() +
                ":fontcolor=" + attr.getFontColor() +
                ":fontsize=" + attr.getFontSize() +
                ":x=(w-text_w)/2" +
                ":y=(h-text_h)/2" +
                ":borderw=2" +
                ":bordercolor=black" +
                ":enable='between(t," + attr.getStartTime() + "," + attr.getEndTime() + ")'\" " +
                "-c:a copy " + attr.getOutputFilePath());
    }

    /**
     * 视频添加音频
     */
    public String videoAddAudio(VideoAddAudioAttributes attr) {
        return MultimediaRuntimeUtils.exec(ffmpegBinPath + "ffmpeg -i " + attr.getVideoFilePath()
                + " -i " + attr.getAudioFilePath() + " -c:v copy -map 0:v:0 -map 1:a:0 -shortest "
                + attr.getOutputFilePath());
    }

    /**
     * 图片转视频带过场动画
     */
    public String img2VideoTransition(Img2VideoTransitionAttributes attr) {
        int size = attr.getImageFilePathList().size();
        BigDecimal imgDu = attr.getVedioDuration().add(new BigDecimal(size).multiply(attr.getTransitionDuration()))
                .subtract(attr.getTransitionDuration())
                .divide(new BigDecimal(size), 2, RoundingMode.HALF_UP);

        StringBuilder sb = new StringBuilder();
        sb.append(ffmpegBinPath).append("ffmpeg");
        for (String imgPath : attr.getImageFilePathList()) {
            sb.append(" -loop 1 -t " + imgDu.doubleValue() + " -i ").append(imgPath);
        }
        sb.append(" -filter_complex \"");
        for (int i = 0; i < size; i++) {
            sb.append("[").append(i).append(":v]scale=1080:1440,setsar=1,fps=60,format=yuv420p[v").append(i).append("];");
        }
        for (int i = 0; i < size - 1; i++) {
            double offset =
                    (imgDu.subtract(attr.getTransitionDuration())).multiply(new BigDecimal(i + 1)).doubleValue();
            if (i == 0) {
                sb.append("[v0][v" + (i + 1) + "]xfade=transition=slideleft:duration=" + attr.getTransitionDuration().doubleValue() +
                        ":offset=" + offset + "[v" + (i + size) + "];");
            } else if (i < size - 2) {
                sb.append("[v" + (i + size - 1) + "][v" + (i + 1) + "]xfade=transition=slideleft:duration=" +
                        attr.getTransitionDuration().doubleValue() + ":offset=" +
                        offset + "[v" + (i + size) + "];");
            } else {
                sb.append("[v" + +(i + size - 1) + "][v" + (i + 1) + "]xfade=transition=slideleft:duration=" +
                        attr.getTransitionDuration().doubleValue() + ":offset=" + offset);
            }
        }
        sb.append("\" -c:v libx264 -b:v 5M -preset slow -crf 18 -r 60 -pix_fmt yuv420p ");
        sb.append(attr.getOutputFilePath());
        return MultimediaRuntimeUtils.exec(sb.toString());
    }

    public static void main(String[] args) throws InterruptedException {
        String folder = "C:/Users/MC/Desktop/ffmpeg/";
        String imgFolder = folder + "0008/";
        String musicFolder = folder + "music/";
        FFmpegClient fFmpegClient = new FFmpegClient("F:/ffmpeg-6.1.1-essentials_build/bin/");
        // 图片转视频
        Img2VideoAttributes attributes = new Img2VideoAttributes();
        attributes.setImgFolderMatch(imgFolder + "image%d.png");
        attributes.setImgSeconds(1.5d);
        attributes.setOutputFilePath(imgFolder + "output_video1.mp4");
        String s1 = fFmpegClient.img2Video(attributes);
        System.out.println("输出1：" + s1);
        // 添加标题
        VideoAddTextAttributes videoAddTextAttributes = new VideoAddTextAttributes();
        videoAddTextAttributes.setInputFilePath(imgFolder + "output_video1.mp4");
        videoAddTextAttributes.setText("【第 5 期】壁纸头像");
        videoAddTextAttributes.setOutputFilePath(imgFolder + "output_video2.mp4");
        String s2 = fFmpegClient.videoAddText(videoAddTextAttributes);
        System.out.println("输出2：" + s2);
        // 添加音乐
        VideoAddAudioAttributes videoAddAudioAttributes = new VideoAddAudioAttributes();
        videoAddAudioAttributes.setVideoFilePath(imgFolder + "output_video2.mp4");
        videoAddAudioAttributes.setAudioFilePath(musicFolder + "shenhaishaonv.mp3");
        videoAddAudioAttributes.setOutputFilePath(imgFolder + "output_video3.mp4");
        String s3 = fFmpegClient.videoAddAudio(videoAddAudioAttributes);
        System.out.println("输出3：" + s3);
        // 多个视频拼接
        String s4 = fFmpegClient.img2VideoTransition(null);
        System.out.println("输出4：" + s4);
    }

}